package com.sp.scmdb.serviceImpl;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.interceptor.Fault;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;
import com.sp.scmdb.bean.PathBean;
import com.sp.scmdb.bean.UserBean;
import com.sp.scmdb.common.CommonParamter;
import com.sp.scmdb.dao.PathDao;
import com.sp.scmdb.entity.Path;
import com.sp.scmdb.service.LogService;
import com.sp.scmdb.service.PathService;
import com.sp.scmdb.spring.ApplicationContext;
import com.sp.scmdb.webservice.model.PathModel;
import com.sp.scmdb.webservice.model.ReturnResponse;
import com.sp.scmdb.webservice.service.UploadDataService;
import com.sp.scmdb.webservice.suport.CastorSerializer;

@Service("pathService")
public class PathServiceImpl implements PathService {

	private static Log log = LogFactory.getLog(PathServiceImpl.class);
	private PathDao pathDao;
	private LogService logs;

	@Required
	public void setLogs(LogService logs) {
		this.logs = logs;
	}

	@Required
	public void setPathDao(PathDao pathDao) {
		this.pathDao = pathDao;
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true,isolation=Isolation.READ_UNCOMMITTED)
	public PathBean queryPathAll(PathBean pathBean, PathBean oldPathBean) {
		List<Path> lists = Lists.newArrayList();
		if (pathBean.equals(oldPathBean)) {
			lists = oldPathBean.getAllList();
		} else {
			lists = pathDao.queryAll();
		}
		if (CollectionUtils.isNotEmpty(lists)) {
			pathBean.setAllList(lists);
			pathBean.setList(lists.subList(pathBean.getCurrentRow(), pathBean.getLastRow()));
		}
		return pathBean;
	}
	
	@Transactional
	public String delPath(String[] arr, UserBean user) {
		String result = CommonParamter.CHECK_FAIL;
		Path path = new Path();
		String name = "";
		for (int i = 0; i < arr.length; i++) {
			path = pathDao.getById(Integer.parseInt(arr[i]));
			if (path != null) {
				name = path.getReaders();
				pathDao.delete(path);
				logs.addLog(user, "删除 路径：\"("+name+")\"成功！");
			}
		}
		result = CommonParamter.CHECK_SUCCESS;
		return result;
	}

	@Transactional
	public String addPath(PathBean pageBean, UserBean user) {
		String result = CommonParamter.CHECK_FAIL;
		Map<String, String> map = getReadersFormPath(pageBean.getPath());
		Path path = new Path();
		path.setPath(pageBean.getPath());
		path.setReaders(map.get("reader"));
		path.setRemark(map.get("remark"));
		pathDao.save(path);
		logs.addLog(user, "添加 路径：\"("+path.getReaders()+")\"成功！");
		result = CommonParamter.CHECK_SUCCESS;
		return result;
	}

	private Map<String, String> getReadersFormPath(String pathStr) {
		Map<String, String> detailMap = new HashMap<String, String>();
		String readers = "";
		String remark = "";
		String posList[] = pathStr.split(";");
		for (String pos : posList) {
			String posDetail[] = pos.split(":");
			if (posDetail[0].indexOf(",") >= 0) {
				if (readers.equals("")) {
					readers = posDetail[0].substring(posDetail[0].indexOf(",") + 1).replace("read", "");
				} else {
					readers = readers + "," + posDetail[0].substring(posDetail[0].indexOf(",") + 1).replace("read", "");
				}
				remark = remark + "["+posDetail[0].substring(posDetail[0].indexOf(",") + 1).replace("read", "") + "]:["
						+ posDetail[1] + "];";
			} else {
				remark = remark + "C:[" + posDetail[1] + "];";
			}
		}
		detailMap.put("reader", readers);
		detailMap.put("remark", remark);
		return detailMap;
	}

	@Transactional(readOnly = true)
	public PathBean queryPathByID(String id) {
		Path path = new Path();
		path = pathDao.getById(Integer.parseInt(id));
		PathBean pathBean = new PathBean();
		pathBean.setPath(path.getPath());
		pathBean.setId(id);
		return pathBean;
	}

	@Transactional
	public String editPath(PathBean pageBean, UserBean user) {
		String result = CommonParamter.CHECK_FAIL;
		Map<String, String> map = getReadersFormPath(pageBean.getPath());
		Path path = new Path();
		path.setId(Integer.parseInt(pageBean.getId()));
		path.setPath(pageBean.getPath());
		path.setReaders(map.get("reader"));
		path.setRemark(map.get("remark"));
		pathDao.update(path);
		logs.addLog(user, "修改 路径：\"("+path.getReaders()+")\"成功！");
		result = CommonParamter.CHECK_SUCCESS;
		return result;
	}
	
	@SuppressWarnings("finally")
	@Transactional(readOnly = true,isolation=Isolation.READ_UNCOMMITTED)
	public String upload(String id) throws Fault{
		String result = CommonParamter.CHECK_FAIL;
		try{
			String Hql = "from Path";
			List<Path> pathList = pathDao.queryHql(Hql);
			List<Path> newpathList = pathDao.queryHql(Hql);
			for (Path path : pathList) {
				path.setPath(path.getRemark());
				newpathList.add(path);
			}
			if(CollectionUtils.isNotEmpty(pathList)){
				PathModel model = new PathModel();
				model.setUserId(CommonParamter.userID);
				model.setPassword(CommonParamter.password);
				model.setListBean(newpathList);
				
				CastorSerializer serializerTool = new CastorSerializer();
				ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
				serializerTool.addMappingLocation("com/sp/scmdb/webservice/mapping/mapping.xml");
				serializerTool.marshal(model, byteOutputStream, "UTF-8");
				String str = new String(byteOutputStream.toByteArray());
				System.out.println("str=================" + str);
				
				UploadDataService upload=(UploadDataService )ApplicationContext.getBean("uploadService");
				result = upload.uploadPath(str);
				ReturnResponse response = (ReturnResponse) serializerTool
				.unmarshal(new ByteArrayInputStream(result.getBytes()),
						"GB2312");
				result = response.getDescription();
			}
		}
		catch(javax.xml.ws.WebServiceException e){
			if ("Could not send Message.".equals(e.getMessage())) {
				result = "timeOut";
			}
		}
		catch(Exception e){
			log.error(e.getMessage());
		}
		finally{
			return result;
		}
	}
}
